//
//  XYHomeController.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 15/12/26.
//  Copyright © 2015年 cn.weibo. All rights reserved.
//

import UIKit
import SVProgressHUD
class XYHomeController: XYBaseController {

    private let HOMECELLID = "homeCellID"
    // 数据容器 懒加载当前视图对应的视图模型
    private lazy var statusList = XYHomeStatusListViewModel.sharedStatusListViewModel
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if login == false {
            let visitorViewModel = XYVisitorViewModel()
            visitorViewModel.icon = "visitordiscover_feed_image_house"
            visitorViewModel.text = "关注一些人，看看有什么惊喜"
            visitorViewModel.isHome = true
            (view as! XYVisitorView).visitorViewModel = visitorViewModel
            return
        }
        setUpNav()
        loadData()
        // 注册通知 － 如果使用 通知中心的 block 监听，其中的 self 一定要 弱引用！
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification,
            object: nil,
            queue: nil) { [weak self] (n) -> Void in
                
                guard let indexPath = n.userInfo?[WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                    return
                }
                guard let urls = n.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else {
                    return
                }
                // 判断 cell 是否遵守了展现动画协议！
                guard let cell = n.object as? PhotoBrowserPresentDelegate else {
                    return
                }
                print("选择 照片 cell \(cell)")
                
                let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
                
                // 1. 设置modal的类型是自定义类型 Transition(转场)
                vc.modalPresentationStyle = UIModalPresentationStyle.Custom
                // 2. 设置动画代理
                vc.transitioningDelegate = self?.photoBrowserAnimator
                // 3. 设置 animator 的代理参数
                self?.photoBrowserAnimator.setDelegateParams(cell, indexPath: indexPath, dismissDelegate: vc)
                // 参数设置所有权交给调用方，一旦调用方失误漏传参数，可能造成不必要的麻烦
                // 会一系列的 ...
                //                self?.photoBrowserAnimator.presentDelegate = cell
                //                self?.photoBrowserAnimator.indexPath = indexPath
                //                self?.photoBrowserAnimator.dismissDelegate = vc
                
                // 3. Modal 展现
                self?.presentViewController(vc, animated: true, completion: nil)
        }
    }
    
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func loadData() {
        
        
        XYHomeStatusListViewModel.sharedStatusListViewModel.loadData(pullUpRefresh.isAnimating()) { (isSuccess, count) -> () in
            
            if isSuccess {
                
                self.tableView.reloadData()
                if self.pullUpRefresh.isAnimating() == false{
                    // 说明是下拉刷新
                    self.showDownTipView(count)
                }
                
            }else{
               SVProgressHUD.showErrorWithStatus("请求失败")
            }
                // 结束刷新
            self.endRefresh()
        }
    }
    
    // 下拉刷新控件的显示
    private func showDownTipView(count:Int) {
        
        // 如果当前正在显示(正在执行动画)，直接返回
        if pullDownTipView.hidden == false {
            return
        }
        
        // 显示
        pullDownTipView.hidden = false
        // 设置数据
        pullDownTipView.text = (count == 0) ? "没有新数据" : "\(count)条新微博"
        
        // 执行动画
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.pullDownTipView.transform = CGAffineTransformMakeTranslation(0, self.pullDownTipView.frame.height)
            //            self.pullDownTipLabel.frame.origin.y += self.pullDownTipLabel.frame.height
            }) { (_) -> Void in
                // 等一秒之后再执行另外的动画
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    //                self.pullDownTipLabel.frame.origin.y -= self.pullDownTipLabel.frame.height
                    self.pullDownTipView.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.pullDownTipView.hidden = true
                })
        }
        
    }
    private func endRefresh() {
        
        
        pullUpRefresh.stopAnimating()
        pullDownRefresh.endRefreshing()
    }
    private func setUpNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", action: "didClickAddFriendBtn", target: self)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", action: "didClickPopBtn", target: self)
        setUpTableView()
    }
    private func setUpTableView() {
        
        tableView.registerClass(XYHomeCell.self, forCellReuseIdentifier: HOMECELLID)
        // 设置tableView 自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        tableView.separatorStyle = .None
        tableView.backgroundColor = UIColor(white: 0.97, alpha: 1)
        tableView.tableFooterView = pullUpRefresh
        pullDownRefresh.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        tableView.addSubview(pullDownRefresh)
    }
    @objc private func didClickPopBtn() {
        let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
        view1.backgroundColor = UIColor.redColor()
        let popMenu = XYPopMenu(content: view1)
        popMenu.frame = UIScreen.mainScreen().bounds
        popMenu.showInRect(CGRect(x: 100, y: 100, width: 100, height: 100))
        
    }
    @objc private func didClickAddFriendBtn() {
        
        print("xxx")
    }
    // 懒加载刷新控件
    private lazy var pullDownTipView: UILabel = {
        
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 14)
        label.backgroundColor = UIColor.orangeColor()
        label.frame.size = CGSize(width: kSCREENWITH, height: 35)
        
        label.textAlignment = .Center
        // 默认隐藏
        label.hidden = true
        // 思考，当前 label 应该添加到哪儿？？？
        if let navigationController = self.navigationController {
            navigationController.view.insertSubview(label, belowSubview: navigationController.navigationBar)
            // 设置位置
            label.frame.origin.y = CGRectGetMaxY(navigationController.navigationBar.frame) - label.frame.height
        }
        return label

    }()
    /// 照片查看转场动画代理
    private lazy var photoBrowserAnimator: PhotoBrowserAnimator = PhotoBrowserAnimator()
    private lazy var pullDownRefresh: XYRefresh = XYRefresh()
    private lazy var pullUpRefresh: UIActivityIndicatorView = {
        let pullUpRefresh = UIActivityIndicatorView()
        pullUpRefresh.activityIndicatorViewStyle = .WhiteLarge
        pullUpRefresh.color = UIColor.purpleColor()
        pullUpRefresh.sizeToFit()
        pullUpRefresh.startAnimating()
        return pullUpRefresh
    }()
}
// MARK: TableView.dataSource and Delete
extension XYHomeController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusList.statusList?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 此处要强转为自定义Cell
        let cell = tableView.dequeueReusableCellWithIdentifier(HOMECELLID, forIndexPath: indexPath) as! XYHomeCell
        let statusViewModel = statusList.statusList![indexPath.row]
        cell.statusViewModel = statusViewModel
        return cell
    }
    override func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        print("xxx")
    }
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusList.statusList!.count - 1 && pullUpRefresh.isAnimating() == false{
            // 开始动画
            pullUpRefresh.startAnimating()
            loadData()
        }
    }
}

